package main

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"
	"time"
)

type DateTime time.Time

func (t *DateTime) MarshalJSON() ([]byte, error) {
	var stamp = fmt.Sprintf("\"%s\"", time.Time(*t).Format("2006-01-02 15:04:05"))
	return []byte(stamp), nil
}

func (t *DateTime) UnmarshalJSON(bytes []byte) error {
	timeStr := strings.Trim(string(bytes), "\"")
	parse, e := time.Parse("2006-01-02 15:04:05", timeStr)
	if e != nil {
		return e
	}
	*t = DateTime(parse)
	return nil
}

type Student struct {
	Name       string   `json:"name"`
	Age        int      `json:"age"`
	CreateTime DateTime `json:"create_time"`
}

func (student *Student) String() string {
	t := time.Time(student.CreateTime)
	return fmt.Sprintf("{Name: %s, Age: %d, CreateTime: %04d-%02d-%02d %02d:%02d:%02d}",
		student.Name,
		student.Age,
		t.Year(),
		t.Month(),
		t.Day(),
		t.Hour(),
		t.Minute(),
		t.Second(),
	)
}

type StudentSlice []*Student

func (slice StudentSlice) Len() int {
	return len(slice)
}

func (slice StudentSlice) Less(i, j int) bool {
	return slice[i].Age < slice[j].Age
}

func (slice StudentSlice) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

func main() {

	// int切片排序
	var arr1 = []int{0, -1, 10, 8, 100, 56}
	sort.Ints(arr1)
	fmt.Println(arr1)

	// 实现Student切片的排序
	slice := make(StudentSlice, 0)
	slice = append(slice,
		&Student{
			Name:       "徐国峰1",
			Age:        30,
			CreateTime: DateTime(time.Now()),
		},
		&Student{
			Name:       "徐国峰2",
			Age:        29,
			CreateTime: DateTime(time.Now()),
		},
		&Student{
			Name:       "徐国峰3",
			Age:        31,
			CreateTime: DateTime(time.Now()),
		},
	)
	fmt.Println(slice)

	// 排序
	sort.Sort(slice)
	fmt.Println(slice)

	// json序列化
	bytes, e := json.Marshal(slice)
	if e != nil {
		fmt.Printf("序列化失败: %v", e)
	} else {
		fmt.Println(string(bytes))
	}

	// 反序列化
	slice2 := make(StudentSlice, 0)
	e = json.Unmarshal(bytes, &slice2)
	if e != nil {
		fmt.Printf("反序列化失败: %v", e)
	} else {
		fmt.Println(slice2)
	}
}
